import { dbUtils } from '../core'

export interface StoreShopComputerRow {
    computer_id: string
    nick_name: string
    real_name: string
    store_id: string
    shop_id: string
    is_delete: number
    create_time: number
}

export const storeShopComputerRepository = {
    upsertBatch(rows: StoreShopComputerRow[]): void {
        if (!rows || rows.length === 0) return
        dbUtils.transaction(() => {
            const cols = ['computer_id', 'nick_name', 'real_name', 'store_id', 'shop_id', 'is_delete', 'create_time']
            const placeholders = cols.map(() => '?').join(', ')
            const updateSet = cols
                .filter(c => c !== 'computer_id')
                .map(c => `${c}=excluded.${c}`)
                .join(', ')

            const sql = `INSERT INTO store_shop_computer (${cols.join(', ')}) VALUES (${placeholders})
            ON CONFLICT(computer_id) DO UPDATE SET ${updateSet}, updated_at=CURRENT_TIMESTAMP`

            for (const r of rows) {
                const vals = [
                    r.computer_id ?? '',
                    r.nick_name ?? '',
                    r.real_name ?? '',
                    r.store_id ?? '0',
                    r.shop_id ?? '0',
                    typeof r.is_delete === 'number' ? r.is_delete : 0,
                    typeof r.create_time === 'number' ? r.create_time : 0
                ]
                dbUtils.execute(sql, vals)
            }
        })
    },

    listByStore(store_id: string, shop_id?: string) {
        if (shop_id) {
            return dbUtils.query(
                `SELECT * FROM store_shop_computer WHERE store_id = ? AND shop_id = ? AND is_delete = 0`,
                [store_id, shop_id]
            )
        }
        return dbUtils.query(
            `SELECT * FROM store_shop_computer WHERE store_id = ? AND is_delete = 0`,
            [store_id]
        )
    }
}

export default storeShopComputerRepository


